package it.asvp.asvp_portal.web.controller;

import it.asvp.asvp_portal.asvp_util.util.Constants;
import it.asvp.asvp_portal.service.services.ConventionService;
import it.asvp.asvp_portal.service.services.PartnerService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;

@Controller
public abstract class BaseController {

	@Autowired
	PartnerService partnerService;
	@Autowired
	ConventionService conventionService;
	
	public UserDetails getUserDetail() throws Exception{
		
		Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		if (principal instanceof UserDetails) {
			return (UserDetails)principal;			
		}
		
		throw new Exception("Utente non autenticato");
	}
	
	 
	 public ModelAndView getErrorModelAndView(Exception e){
		 
		    ModelAndView mv=getModelAndView("error");
			mv.addObject("message",e.getMessage());
			return mv;
	 }
	 
	 public ModelAndView getModelAndView(String viewName){
		 
		 ModelAndView mv = new ModelAndView(viewName);
		 mv.addObject(Constants.Partner.PARTNERS, partnerService.getAllPartners());
		 mv.addObject(Constants.Convention.ACTIVE_CONVENTIONS, conventionService.getByActive(true));
		 
		 return mv;
	 }
	 
}
